package com.web.test.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.web.test.mapper.UserMapper;
import com.web.test.pojo.User;
import com.web.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.*;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("{url}.html")
    public String login(@PathVariable String url){
        return url;
    }

    //登录业务
    @RequestMapping("/doLogin")
    public String doLogin(String username, String password, String valideCode, Model model, HttpSession session){
        //1.验证码判断
        String vrifyCode=(String) session.getAttribute("vrifyCode");
        if(!valideCode.equals(vrifyCode)){
            model.addAttribute("errorMsg","验证码错误");
            return "login";
        }
        //2.登录用户信息验证
        User loginUser= userService.login(username,password);
        if(loginUser!=null){
            if(loginUser.getUserisadmin()==0){
                session.setAttribute("user",loginUser);
                model.addAttribute("username",loginUser.getUsername());
                return "index";
            }else if(loginUser.getUserisadmin()==1){
                session.setAttribute("user",loginUser);
                model.addAttribute("username",loginUser.getUsername());
                return "manager";
            }else{
                session.setAttribute("user",loginUser);
                model.addAttribute("username",loginUser.getUsername());
                return "redirect:/queryUsers";
            }
        }else{
            model.addAttribute("errorMsg","账号或密码错误");
            return "login";
        }
    }


    //注册业务
    @RequestMapping("/doRegister")
    public String doRegister(User user, Model model){
        if(user.getUsername()==""){
            model.addAttribute("errorMsg","用户名不能为空");
            return "register";
        }else if(user.getUserpassword()==""){
            model.addAttribute("errorMsg","密码不能为空");
            return "register";
        }else if(user.getUserisadmin()==null){
            model.addAttribute("errorMsg","身份信息不能为空");
            return "register";
        }else{
            userService.addUser(user);
            return "login";
        }
    }


    //退出登陆业务
    @RequestMapping("/doLogout")
    public String doLogout(HttpSession session){
        session.invalidate();
        return "login";
    }

    //获取数据列表
    @GetMapping("/queryUsers")
    public ModelAndView queryUsers(){
        List<User> List=userService.queryUsers();
        List<User> managerList1=new ArrayList<>();
        List<User> List1=new ArrayList<>();
        ModelAndView mv=new ModelAndView();
        for (int i = 0; i < List.size(); i++) {
            if(List.get(i).getUserisadmin()==1){
                managerList1.add(List.get(i));
            }
        };
        for (int i = 0; i < List.size(); i++) {
            if(List.get(i).getUserisadmin()==0){
                List1.add(List.get(i));
            }
        };
        mv.addObject("managerList",managerList1);
        mv.addObject("userList",List1);
        mv.setViewName("superManager");
        return mv;
    }

    //删除用户业务
    @RequestMapping("/deleteUser")
    public String deleteUser(Integer userid){
        userService.deleteUser(userid);
        System.out.println("我已经成功删除");
        return "redirect:/queryUsers";
    }




    @Autowired
    private DefaultKaptcha captchaProducer;

    /**
     * 获取验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        //ByteArrayOutputStream 对byte类型数据进行写入的类 相当于一个中间缓冲层，将类写入到文件等其他outputStream。它是对字节进行操作，属于内存操作流
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String createText = captchaProducer.createText();
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = captchaProducer.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    //检查用户名是否可用
    @RequestMapping("/checkUserExist")
    @ResponseBody //把java类型对象转化成json对象，返回到前端
    public Map<String,String> checkUserExist(String username){
        boolean result= userService.checkUserExist(username);
        Map<String,String> map=new HashMap<>();
        if(result){
            map.put("msg","用户名已存在");
        }else {
            map.put("msg","用户名可用");
        }
        return map;
    }

    @RequestMapping("/cancelUser")
    @ResponseBody //把java类型对象转化成json对象，返回到前端
    public String cancelUser(Integer userid){
        User user = new User();
        user.setUserisadmin(0);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid",userid);
        userMapper.update(user,queryWrapper);
        return "redirect:/queryUsers";
    }


    @RequestMapping("/addUser")
    @ResponseBody //把java类型对象转化成json对象，返回到前端
    public String addUser(Integer userid){
        User user = new User();
        user.setUserisadmin(1);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid",userid);
        userMapper.update(user,queryWrapper);
        return "redirect:/queryUsers";
    }

}
